package com.ingenio.siot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.ingenio.siot.adapter.SchedulerAdapter;
import com.ingenio.siot.entity.Punto;

public class Scheduler extends TimerTask{
	
	private Date now;
	private Punto punto;
	private static Scheduler s;
	
	private void sendPost() throws Exception {
		URL url = new URL("http://localhost:8080/siot/almacenarObservaciones");
	    URLConnection conn = url.openConnection();
	    conn.setDoOutput(true);
	    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

	    writer.write("lat="+punto.getLatitud()+"&lng="+punto.getLongitud()+"&velocidad="+punto.getVelocidad()+"&id_movil="+punto.getId_movil()+"&fecha="+punto.getFecha());
	    writer.flush();
	    String line;
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    while ((line = reader.readLine()) != null) {
	      System.out.println(line);
	    }
	    writer.close();
	    reader.close();
	}
	
	public void run() {
		SchedulerAdapter sa = new SchedulerAdapter();
		now = new Date();
		try {
		  List<Punto> puntos = sa.obtenerObservaciones(now);
		  if(puntos.size() > 0){
			  for (Punto p : puntos) {
				   this.punto = p;
				   s.sendPost();
			  }
		  }	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException {
		Timer time = new Timer(); 
		s = new Scheduler(); 
		time.schedule(s, 0, 1000); 
 	}

}
